package cn.edu.tyu.finance.thingstype.servlet;

import cn.edu.tyu.util.DbUtil;
import cn.edu.tyu.util.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户登录Servlet
 * @author liyanrong
 * @version 1.0
 */
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    /**
     * 处理网页发来的post
     * 请求
     * @param request 请求对象
     * @param response 响应对象
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接受用户名和密码
        String uname = request.getParameter("username");
        String upsw = request.getParameter("upsw");
        String upswMD5 = StringUtil.getMD5("upsw");
        //2.连接数据库，查询有无此人
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        conn = DbUtil.getConnection();
        String sql = "SELECT * FROM users WHERE username=? AND userpsw=?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,uname);
            pstmt.setString(2,upswMD5);
            rs = pstmt.executeQuery();
            if (rs.next()){
                response.sendRedirect("ok.jsp");
            } else{
                response.sendRedirect("fail.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DbUtil.backConn(conn,pstmt,rs);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
